package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*") // 拦截所有请求
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        如果只拦截请求 而不放行 也不能获取到资料
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        首先判断是否为登录操作 如果是 则直接放行 如果不是 则获取token 如果不存在 直接错误 存在就解析令牌 如果解析成功就直接放行
        System.out.println("拦截到请求");
//        获取请求url地址
        String url = request.getRequestURI().toString();
        log.info("请求的url,{}", url);
        if (url.contains("login")) {
            log.info("登陆操作");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空");
//            要将其转换为json
            Result err = Result.Error("NOT_LOGIN");
            String nologin = JSONObject.toJSONString(err);
            response.getWriter().write(nologin);
            return;
        }
//        校验jwt令牌
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) { // 解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result err = Result.Error("NOT_LOGIN");
            String nologin = JSONObject.toJSONString(err);
            response.getWriter().write(nologin);
            return;
        }
//       令牌解析成功 放行
        log.info("令牌解析成功,放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
